<template>
  <div id="TaskEdit">
    <div class="container">
      <a-form-model
        ref="form"
        class="edit-form"
        :rules="rules"
        :model="form"
      >
        <a-form-model-item label="任务名称" prop="taskName" class="form-col">
          <a-input v-model="form.taskName" placeholder="请输入任务名称"></a-input>
        </a-form-model-item>
        <a-form-model-item label="任务类型" prop="taskType" class="form-col">
          <a-radio-group v-model="form.taskType">
            <a-radio value="LS"> 临时任务 </a-radio>
            <a-radio value="DS"> 定期任务 </a-radio>
          </a-radio-group>
        </a-form-model-item>
        <a-form-model-item label="完成时限" prop="okTime" class="form-col">
          <a-date-picker
            v-model="form.okTime"
            clearable
            placeholder="请选择"
            valueFormat="YYYY-MM-DD HH:mm:ss"
            :show-time="{ defaultValue: $moment('00:00:00', 'HH:mm:ss') }"
          >
          </a-date-picker>
        </a-form-model-item>
        <a-form-model-item label="选择项目" prop="itemsId" class="form-col">
          <a-select v-model="form.itemsId" allowClear placeholder="请选择项目" @change="selectItem">
            <a-select-option
              v-for="item in projectList"
              :key="item.ncProjectName"
              :value="item.ncProjectId"
              >
              {{ item.ncProjectName }}
            </a-select-option>
          </a-select>
        </a-form-model-item>
        <a-form-model-item label="触发时间" class="form-col" prop="cfTime" v-if="form.taskType === 'DS'">
          <a-date-picker v-model="form.cfTime" clearable placeholder="请选择时间" valueFormat="DD" >
          </a-date-picker>
        </a-form-model-item>
        <a-form-model-item label="过期时间" prop="outTime" v-if="form.taskType === 'DS'" class="form-col">
          <a-date-picker
            v-model="form.outTime"
            clearable
            placeholder="请选择"
            valueFormat="YYYY-MM-DD HH:mm:ss"
            :show-time="{ defaultValue: $moment('00:00:00', 'HH:mm:ss') }"
          >
          </a-date-picker>
        </a-form-model-item>
        <a-form-model-item label="执行角色" prop="roleId" class="form-col">
          <a-select v-model="form.roleId" allowClear placeholder="请选择执行角色">
            <a-select-option
              v-for="item in roleList"
              :key="item.roleId"
              :value="item.roleId"
              >{{ item.roleName }}</a-select-option
            >
          </a-select>
        </a-form-model-item>
        <a-form-model-item label="审批流程" prop="checkCopySendList" class="form-col">
          <!-- <span>① 审核人：</span><span>{{form.userInfo.userName || '未知'}}</span> -->
          <div>审核人：
            <a-tag
              v-for="(item, index) in checkCopySendList" :key="index"
              closable
              @close.prevent="handleDeleteTag(2, item, index)"
            >
              {{item.label}}
            </a-tag>
            <a-button
              type="primary"
              shape="circle"
              icon="plus"
              ghost
              @click="handleShowModal"
              size="small"
            />
          </div>
        </a-form-model-item>
        <a-form-model-item label="任务说明" prop="countingTaskExplain" class="form-col">
          <a-textarea
            v-model="form.countingTaskExplain"
            placeholder="请输入任务说明"
            :auto-size="{ minRows: 3, maxRows: 5 }"
          />
        </a-form-model-item>
        <a-form-model-item
          label="相关附件"
          prop="userFile"
          class="form-col col-100 column"
        >
          <Btns :data="btns" justify="flex-start" />
          <p class="form-tip">支持扩展名: .excel .doc .docx .pdf .jpg .png</p>
          <div v-if="showUploadList.length">上传文件:</div>
          <div v-if="showUploadList.length">
            <div v-for="(item, index) in showUploadList" :key="index">{{item.url}}</div>
          </div>
        </a-form-model-item>
        <a-button type="primary" @click="submitTask">保存</a-button>
      </a-form-model>
    </div>

    <a-modal
      title="添加审批人"
      :visible="dialog.visibleCopySend"
      class="common-dialog flow-detail"
      width="520px"
      :afterClose="copySendAfterClose"
      @cancel="dialog.visibleCopySend = false"
    >
      <div>
        <div class="flex no-center">
          <div class="choose">
            <a-row type="flex" justify="space-between">
              <a-col>
                <div class="radio-title">选择角色</div>
              </a-col>
            </a-row>
            <a-radio-group v-model="form.roleValue" @change="onChange">
              <a-radio :style="radioStyle" v-for="(item, index) in copySend" :key="index" :value="item.value">
                {{item.label}}
              </a-radio>
            </a-radio-group>
            <!-- <a-checkbox
              v-for="(item, index) in copySend"
              :checked="item.checked"
              :key="index"
              :value="item.value"
              @change="handleCheck(item, $event)"
            >
              <span class="send-check-span" @click.prevent="handleRoleFocus(item)">{{
                item.label
              }}</span> -->
            <!-- </a-checkbox> -->
          </div>
          <div class="gm">
            <a-row type="flex" justify="space-between">
              <a-col>
                <div class="radio-title">选择成员</div>
              </a-col>
            </a-row>
            <a-radio-group v-model="form.checkCopySendList" @change="onChange">
              <a-radio :style="radioStyle" v-for="(item, index) in rightcopySendList" :key="index" :value="item.value">
                {{item.label}}
              </a-radio>
            </a-radio-group>
              <!-- <a-checkbox
                v-for="(item, index) in rightcopySendList"
                :key="index"
                :value="item.value"
                :checked="item.checked"
                @change="handleChangeChecked(item, $event, 'send')"
                >{{ item.label }}
              </a-checkbox> -->
          </div>
        </div>
      </div>
      <div slot="footer" class="dialog-footer">
        <a-button @click="handleShowDialog">取 消</a-button>
        <a-button type="primary" @click="handleCopySendConfirm">确 定</a-button>
      </div>
    </a-modal>
  </div>
</template>

<script lang="ts">
import { Validate } from '@/decorator';
import { Component, Vue, Watch } from 'vue-property-decorator';

@Component
export default class TaskEdit extends Vue {
  form: any = {
    taskName: '',
    taskType: 'LS',
    okTime: '',
    cfTime: '',
    outTime: '',
    userInfo: {},
    checkCopySendList: [],
    itemsId: undefined,
    roleId: undefined,
    countingTaskExplain: '',
    roleValue: '',
    itemsName: ''
  };
  countingTaskFileList: any = [] // 任务附件
  rules: any = {
    taskName: [{ required: true, message: '请输入任务名称', trigger: 'blur' }],
    taskType: [{ required: true, message: '请选择任务类型', trigger: 'change' }],
    okTime: [{ required: true, message: '请选择完成时限', trigger: 'change' }],
    cfTime: [{ required: true, message: '请选择触发时间', trigger: 'change' }],
    roleId: [{ required: true, message: '请输入执行角色', trigger: 'change' }],
    itemsId: [{ required: true, message: '请选择项目', trigger: 'change' }],
    checkCopySendList: [{ required: true, message: '请选择审批人', trigger: 'change' }],
    countingTaskExplain: [{ required: true, message: '请输入任务说明', trigger: 'blur' }]
  };
  projectList: any = [] // 项目列表
  roleList: any = [] // 角色列表
  btns: any[] = [
    {
      label: '上传文件',
      upload: true,
      accept: '.doc,.docx,.rar,.zip,.pdf,.jpg,.png',
      callback: (res: any) => this.uploadSuccess(res.fileList)
    }
  ]
  showUploadList: any = [] // 上传完图片展示
  // 审批人modal
  List: any[] = [];
  copySend: any[] = [];
  rightcopySendList: any = []; // 抄送人右边数据
  checkCopySendList: any[] = []
  dialog: any = {
    visible: false,
    visibleCopySend: false,
    title: '添加审批人'
  };
  radioStyle: any= {
    display: 'block',
    height: '30px',
    lineHeight: '30px'
  }
  // checkAddList (rule: any, value: any, callback: any) {
  //   if (!this.checkCopySendList.length) {
  //     return callback(new Error('请选择审批人'))
  //   }
  //   callback()
  // }
  get taskId () {
    return this.$route.query.taskId
  }
  init () {
    this.form.userInfo = JSON.parse(localStorage.getItem('userInfo') || '{}')
    this.getProjectList()
    this.getRoleList()
    this.getApproveList()
    if (this.taskId) {
      this.getDetail()
      this.getFile()
    }
  }
  // 选择项目
  selectItem (val:any) {
    this.projectList.forEach((item:any) => {
      if (item.ncProjectId == val) {
        this.form.itemsName = item.ncProjectName
      }
    })
  }
  // 详情
  getDetail () {
    let data = { taskId: this.taskId }
    this.$api.countingTaskDetailFetch(data).then((res: any) => {
      let {taskName, okTime, taskType, cfTime, outTime, itemsId, roleId, countingTaskExplain, roleValue} = res.data
      this.form = {
        taskName,
        okTime,
        taskType,
        cfTime,
        outTime,
        itemsId,
        roleId,
        countingTaskExplain,
        roleValue,
        checkCopySendList: []
      }
      this.$api.countingTaskApprovalFetch({taskId: res.data.taskId}).then((data:any) => {
        let {approvalId, auditId, auditName, roleId, roleName, taskId} = data.data[0]
        this.checkCopySendList = [{value: auditId, label: auditName, approvalId, roleId, roleName, taskId }]
        this.checkCopySendList.forEach((item:any) => {
          this.form.checkCopySendList.push(item)
        })
      })
      this.form.userInfo = JSON.parse(localStorage.getItem('userInfo') || '{}')
    })
  }
  // 附件
  getFile () {
    let data = { taskId: this.taskId }
    this.$api.countingTaskDetailFileListFetch(data).then((res: any) => {
      this.countingTaskFileList = res.data.map((item: any, index: number) => ({
        uid: -index - 1,
        url: item.picUrl,
        name: item.picUrl
      }))
      this.showUploadList = this.countingTaskFileList
    })
  }
  // 项目列表
  getProjectList () {
    let data = {
      page: 1,
      size: 9999
    }
    this.$api.projectRoleProjectListFetch(data).then((res: any) => {
      this.projectList = res.data.records
    })
  }
  // 角色列表
  getRoleList () {
    let data = {
      page: 1,
      size: 99999999,
      status: 1,
      searchValue: ''
    }
    this.$api.adminRoleRoleListFetch(data).then((res: any) => {
      this.roleList = res.data.records
    })
  }
  uploadSuccess (fileList: any) {
    this.countingTaskFileList = fileList;
    let list = JSON.parse(JSON.stringify(this.countingTaskFileList))
    this.showUploadList = list.map((item: any) => ({
      url: this.$util.getPicUrl(item)
    }))
  }
  timeChange (time: any) {
    let timestamp = new Date(time);
    let date = timestamp.getDate()
    return date
  }

  @Validate('form')
  submitTask () {
    let taskFile = this.countingTaskFileList.map((item: any) => ({
      url: this.$util.getPicUrl(item)
    }))
    let { taskType, outTime, cfTime, userInfo } = this.form
    if (taskType === 'DS') {
      this.form.outTime = this.form.outTime ? this.form.outTime : null
      // this.form.cfTime = this.timeChange(cfTime)
      this.form.cfTime = this.form.cfTime ? this.form.cfTime : null
    } else {
      this.form.outTime = ''
      this.form.cfTime = ''
    }

    this.projectList.forEach((item:any) => {
      if (item.ncProjectId == this.form.itemsId) {
        this.form.itemsName = item.ncProjectName
      }
    })

    console.log(this.form, 'this.formthis.formthis.form')

    let countingTaskApproval = [
      // {
      //   auditId: userInfo.adminId,
      //   auditName: userInfo.userName,
      //   roleId: userInfo.roleId,
      //   roleName: userInfo.roleName,
      //   sort: 0
      // },
      {
        auditId: this.checkCopySendList[0].admin_id || this.checkCopySendList[0].value,
        auditName: this.checkCopySendList[0].user_name || this.checkCopySendList[0].label,
        roleId: this.checkCopySendList[0].role_id || this.checkCopySendList[0].roleId,
        roleName: this.checkCopySendList[0].role_name || this.checkCopySendList[0].roleName,
        sort: 1
      }
    ]
    let data = {
      countingTask: this.form,
      countingTaskApproval,
      countingTaskFileList: taskFile
    }
    delete data.countingTask.userInfo
    delete data.countingTask.checkCopySendList
    if (this.taskId) {
      data.countingTask.taskId = this.taskId
      this.$api.countingUpdateTaskFetch(data).then(() => {
        this.$message.success('保存成功')
        this.$router.push({ path: '/allot/task' })
      })
    } else {
      this.$api.countingSaveTaskFetch(data).then(() => {
      this.$message.success('保存成功')
      this.$router.push({ path: '/allot/task' })
    })
    }
  }

  getApproveList () {
    this.$api.approveListRoleFetch().then(({data}: any) => {
      this.List = data
      this.copySend = data.map((item: any) => {
        item.label = item.role_name
        item.value = item.role_id
        return item
      })

      this.rightcopySendList = data[0].rroleAdminUserAddList.map((item: any) => {
        item.label = item.user_name
        item.value = item.admin_id
        return item
      })
      if (!this.taskId) {
        this.form.roleValue = this.copySend[0].value
        this.form.checkCopySendList = this.rightcopySendList[0].value
      }
    })
  }
  onChange (e:any) {
    this.List.filter((item2:any) => { return item2.role_id === e.target.value }).map((item3:any) => {
      this.rightcopySendList = item3.rroleAdminUserAddList.map((item4:any) => {
        item4.label = item4.user_name
        item4.value = item4.admin_id
      return item4
      })
    })
  }
  handleShowModal () {
    this.dialog.visibleCopySend = true
  }
  // 显示新增编辑的dialog
  handleShowDialog () {
    this.dialog.visibleCopySend = false
  }
  handleDeleteTag (type: number, item: any, index: number): void {
    this.checkCopySendList.splice(index, 1)
    // 编辑
    // if (this.taskId) {
    //   let idx = this.form.rroleAdminUserAddList.findIndex((ele: any) => item.value === ele.value)
    //   this.form.rroleAdminUserAddList.splice(idx, 1)
    // }
    // this.copySend.forEach((ele) => {
    //   let final = ele.rroleAdminUserAddList.find((child: any) => child.admin_id === item.admin_id)
    //   final && (final.checked = false)
    // })
  }
  // 抄送人modal的确定
  handleCopySendConfirm (): void {
    let temp: any[] = []

    console.log(this.form, 'this.formthis.form')

    this.copySend.map((item) => {
      item.rroleAdminUserAddList && item.rroleAdminUserAddList.forEach((child: any) => {
        if (child.value === this.form.checkCopySendList) {
          temp.push(child)
          temp[0].role_name = item.role_name
        }
      })
    })




    this.checkCopySendList = JSON.parse(JSON.stringify(temp))
    this.handleShowDialog()
  }
  // 抄送人madal关闭
  copySendAfterClose () {
    // 如果是取消，或者点击背景关闭。则选择的checkbox和tag保持一致
    // this.copySend.map((item) => {
    //   item.children && item.children.forEach((child: any) => {
    //     this.checkCopySendList.forEach((ele) => {
    //       if (child.admin_id === ele.admin_id) {
    //         child.checked = ele.checked
    //       }
    //     })
    //   })
    // })
  }
}
</script>

<style lang="scss" scoped>
#TaskEdit {
}
.form-row {
  display: flex;
  flex-wrap: wrap;
  .form-col {
    width: 50%;
    flex-shrink: 0;
    // margin-right: 10px;
    &.col-100 {
      width: 100%;
    }
    &.column {
      .el-form-item__content {
        flex-direction: column;
      }
    }
    .el-form-item__content {
      display: flex;
    }
    :nth-of-type(3n) {
      margin-right: 0;
    }
    .el-date-editor.el-input,
    .el-date-editor.el-input__inner {
      width: 100%;
    }
    .el-select {
      .el-input {
        width: 100%;
      }
    }
    .form-tip {
      color: #999;
    }
  }
}
.flow-detail {
  .ant-modal {
    .flex {
      padding: 10px 20px;
      border: 1px solid #c7c7c7;
      align-items: flex-start;
      .choose,
      .gm {
        width: 50%;
        border-right: 1px solid #c7c7c7;
        /deep/.ant-radio-wrapper,
        /deep/.ant-checkbox-wrapper {
          display: block;
          margin-bottom: 10px;
          margin-left: 0;
        }
      }
      .gm {
        border: none;
        padding-left: 20px;
      }
    }
  }
}
.radio-title {
  font-weight: 600;
  font-size: 15px;
  margin-bottom: 5px;
}
.send-check-span {
  padding: 5px 15px 5px 5px;
}
</style>
